package br.com.merks;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.com.merks.model.User;
import br.com.yx.vraptor.security.Audit;
import br.com.yx.vraptor.security.SecurityHandler;

@Component
public class AuditImpl implements Audit {
	public static final Logger logger = Logger.getLogger(AuditImpl.class);
	private HttpServletRequest request;
	private SecurityHandler<User> loginHandler;
	public AuditImpl(HttpServletRequest request, SecurityHandler<User> loginHandler) {
		this.request = request;
		this.loginHandler = loginHandler;
	}

	public void allowed(ResourceMethod method, Object resourceInstance) {
		if (logger.isDebugEnabled()) {
			if (this.loginHandler.getUser()!=null) {
			logger.debug("Allowing user " + this.loginHandler.getUser().getEmail() + "("+ this.request.getRemoteAddr() + ") to access " + method.getMethod().getDeclaringClass().getName() + "." + method.getMethod().getName() + "()");
			} else {
				logger.debug("Allowing user ("+ this.request.getRemoteAddr() + ") to access " + method.getMethod().getDeclaringClass().getName() + "." + method.getMethod().getName() + "()");
			}
		}
	}

	public void denied(ResourceMethod method, Object resourceInstance) {
		if (logger.isDebugEnabled()) {
		if (this.loginHandler.getUser()!=null) {
			logger.warn("Blocking user " + this.loginHandler.getUser().getEmail() + "("+ this.request.getRemoteAddr() + ")  to access " + method.getMethod().getDeclaringClass().getName() + "." + method.getMethod().getName() + "()");
		} else {
			logger.warn("Blocking user ("+ this.request.getRemoteAddr() + ") to access " + method.getMethod().getDeclaringClass().getName() + "." + method.getMethod().getName() + "()");
		}
		}
		
	}

}
